import functools
import os
import signal
import threading

# default_executor = None

# def __import__():
#     default_executor = futures.ThreadPoolExecutor(1)
#     print("init executor!!!!!!!!!!")


def default_timeout_handle():
    raise TimeoutError('执行函数超时')


# 方法超时注解
def func_timeout(timeout, callback=default_timeout_handle):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            if os.name == 'nt':  # Windows
                # 使用 threading 来实现超时功能
                result = [Exception('执行函数超时')]

                def target():
                    try:
                        result[0] = func(*args, **kwargs)
                    except Exception as e:
                        result[0] = e
                thread = threading.Thread(target=target)
                thread.start()
                thread.join(timeout)
                if thread.is_alive():
                    callback()
                    thread.join()  # 确保子线程能够退出
                if isinstance(result[0], Exception):
                    raise result[0]
                return result[0]
            else:  # Unix/Linux
                def handle(signum, frame):
                    callback()
                old_handler = signal.signal(signal.SIGALRM, handle)
                signal.alarm(timeout)
                try:
                    result = func(*args, **kwargs)
                finally:
                    signal.signal(signal.SIGALRM, old_handler)
                    signal.alarm(0)
                return result
        return wrapper
    return decorator